package com.blog.util;


import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @description:
 * @author: JinFeng.Huang
 * @create: 2018-09-06 11:15
 **/
public class MachineUtil {

    /**
     * 分页设置
     */
    //页数
    public final static int PAGE_CURRENT = 1;
    //大小
    public final static int PAGE_SIZE = 10;

    /**
     * ajax 返回
     * @param response
     * @param msg
     * @throws IOException
     */
    public static void printMsg(HttpServletResponse response, String msg) throws IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        response.getWriter().write(msg);
    }

    /**
     * 返回客户端数据
     *
     * @param response
     * @param obj
     */
    public static void print(HttpServletResponse response, Object obj) {

        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        try {
            PrintWriter out = response.getWriter();
            out.println(JSONObject.fromObject(obj));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * JSONObject检查里面的key是否为空
     */
    private static boolean isNotNull(JSONObject obj, String key){
        if(obj==null||obj.optBoolean(key)||obj.get(key)==null||obj.getString(key).equals("null")){
            return false;
        }else{
            return true;
        }
    }

    public static double isNullBigDecimeb(BigDecimal b){
        if(b==null){
            return 0.0;
        }else{
            return b.doubleValue();
        }
    }

    //将BigDecimal转换double并保留2位小数
    public static String big_dec_2(Object obj){
        DecimalFormat df = new DecimalFormat("#.00");
        BigDecimal object = (BigDecimal)obj;
        return df.format(object.doubleValue());
    }

    /**
     * 1.判断是否为空
     */
    public static boolean isNull(Object obj){
        if(obj!=null&&!String.valueOf(obj).equals("null")&&!String.valueOf(obj).equals("")){
            return false;
        }else{
            return true;
        }
    }
}